<template>
  <div
    ref="mapContainer"
    class="map-container"
    :class="{ 
      readonly: !editable, 
      'no-controls': !editable && !showFullscreen,
      'small-size': height === '300px', 
      'fullscreen': isFullscreen 
    }"
  >
    <!-- 地图容器 -->
    <div
      ref="mapWrapper"
      class="map-wrapper"
      :style="{ height: height }"
    ></div>

    <!-- 加载遮罩 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <div class="loading-text">地图加载中...</div>
      </div>
    </div>

    <!-- 操作控制面板 -->
    <div v-if="editable || showFullscreen" class="map-controls">
      <!-- 编辑相关按钮（仅在可编辑模式下显示） -->
      <template v-if="editable">
        <el-button
          type="primary"
          size="small"
          @click="startFenceEdit"
          :loading="isEditing"
          icon="el-icon-edit"
        >
          {{ isEditing ? "编辑中" : "设置围栏" }}
        </el-button>

        <el-button
          v-if="isEditing"
          type="success"
          size="small"
          @click="finishEdit"
          icon="el-icon-check"
        >
          完成
        </el-button>

        <el-button
          v-if="isEditing"
          type="info"
          size="small"
          @click="cancelEdit"
          icon="el-icon-close"
        >
          取消
        </el-button>
      </template>

      <!-- 全屏按钮（在非编辑状态下显示，或者在只读模式下显示） -->
      <el-button
        v-if="showFullscreen && (!editable || !isEditing)"
        type="default"
        size="small"
        @click="toggleFullscreen"
        :icon="isFullscreen ? 'el-icon-minus' : 'el-icon-full-screen'"
        :title="isFullscreen ? '退出全屏' : '全屏显示'"
      >
        {{ isFullscreen ? "退出全屏" : "全屏" }}
      </el-button>
    </div>

    <!-- 调试信息（开发时使用） -->
    <!-- <div style="position: absolute; top: 10px; left: 10px; background: rgba(0,0,0,0.7); color: white; padding: 5px; font-size: 12px; z-index: 1000;">
      editable: {{ editable }}<br>
      showFullscreen: {{ showFullscreen }}<br>
      isEditing: {{ isEditing }}<br>
      控制面板显示: {{ editable || showFullscreen }}<br>
      全屏按钮显示: {{ showFullscreen && (!editable || !isEditing) }}
    </div> -->

    <!-- 提示信息 -->
    <div v-if="isEditing" class="edit-tips">
      <div class="tips-content">
        <span class="tip-text">
          <i class="el-icon-info"></i>
          左键添加顶点 | 至少3个点 | 右键或点击完成结束
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import {
  loadAMapScript,
  validateCoordinates,
  getPolygonCenter,
} from "./map-utils";
import FenceManager from "./fence-manager";
import "./style.scss";

export default {
  name: "MapContainer",
  props: {
    // 地图中心坐标
    center: {
      type: Array,
      default: () => [116.397428, 39.90923], // 北京坐标
      validator: (value) => value.length === 2,
    },

    // 地图缩放级别
    zoom: {
      type: Number,
      default: 13,
      validator: (value) => value >= 3 && value <= 18,
    },

    // 电子围栏坐标数组
    fenceCoordinates: {
      type: Array,
      default: () => [],
      validator: (value) => {
        if (!Array.isArray(value)) return false;
        if (value.length === 0) return true;
        return validateCoordinates(value);
      },
    },

    // 地图容器高度
    height: {
      type: String,
      default: "400px",
    },

    // 是否可编辑围栏
    editable: {
      type: Boolean,
      default: true,
    },

    // 是否显示全屏按钮
    showFullscreen: {
      type: Boolean,
      default: true,
    },

    // 围栏样式配置
    fenceStyle: {
      type: Object,
      default: () => ({
        strokeColor: "#3366FF",
        strokeWeight: 2,
        fillColor: "#3366FF",
        fillOpacity: 0.2,
      }),
    },
  },

  data() {
    return {
      map: null, // 地图实例
      fenceManager: null, // 围栏管理器
      isEditing: false, // 是否正在编辑围栏
      hasFence: false, // 是否有围栏
      loading: true, // 是否正在加载
      isFullscreen: false, // 是否全屏状态
    };
  },

  async mounted() {
    await this.initMap();
    this.initFence();
    this.loading = false;
    this.initFullscreenListener();
  },

  watch: {
    fenceCoordinates: {
      handler(newCoordinates) {
        this.updateFenceDisplay(newCoordinates);
      },
      deep: true,
      immediate: true,
    },

    center(newCenter) {
      if (this.map && newCenter) {
        this.map.setCenter(newCenter);
      }
    },

    zoom(newZoom) {
      if (this.map && newZoom) {
        this.map.setZoom(newZoom);
      }
    },

    fenceStyle: {
      handler(newStyle) {
        if (this.fenceManager && newStyle) {
          this.fenceManager.updateStyle(newStyle);
        }
      },
      deep: true,
    },
  },

  methods: {
    // 初始化地图
    async initMap() {
      try {
        await loadAMapScript();

        // 计算地图中心点
        let mapCenter = this.center;
        let mapZoom = this.zoom;
        
        if (this.fenceCoordinates && this.fenceCoordinates.length > 0) {
          const fenceCenter = getPolygonCenter(this.fenceCoordinates);
          // 只有当围栏中心不是默认北京坐标时才使用围栏中心
          if (fenceCenter[0] !== 116.397428 || fenceCenter[1] !== 39.90923) {
            mapCenter = fenceCenter;
            // 如果有围栏，使用稍微放大的缩放级别以显示围栏全貌
            mapZoom = 15;
          }
        }

        this.map = new AMap.Map(this.$refs.mapWrapper, {
          center: mapCenter,
          zoom: mapZoom,
          resizeEnable: true,
          rotateEnable: false,
          mapStyle: "amap://styles/whitesmoke",
          features: ["bg", "road", "building", "point"],
        });

        // // 添加地图控件
        // this.map.addControl(new AMap.Scale())
        // this.map.addControl(new AMap.ToolBar({
        //   position: 'LT'
        // }))

        this.$emit("map-loaded", this.map);
      } catch (error) {
        console.error("地图初始化失败:", error);
        this.$message && this.$message.error("地图加载失败，请检查网络连接");
        this.loading = false;
      }
    },

    // 初始化围栏管理器
    initFence() {
      if (!this.map) return;

      this.fenceManager = new FenceManager({
        map: this.map,
        style: this.fenceStyle,
        onFenceChange: this.handleFenceChange,
        onEditStart: () => {
          this.isEditing = true;
          this.$emit("edit-start");
        },
        onEditEnd: () => {
          this.isEditing = false;
          this.$emit("edit-end");
        },
      });

      // 如果有初始围栏数据，则显示
      if (this.fenceCoordinates && this.fenceCoordinates.length > 0) {
        this.updateFenceDisplay(this.fenceCoordinates);
      }
    },

    // 初始化全屏状态监听
    initFullscreenListener() {
      this.handleFullscreenChange = () => {
        const isFullscreen = !!(
          document.fullscreenElement ||
          document.webkitFullscreenElement ||
          document.mozFullScreenElement ||
          document.msFullscreenElement
        );
        
        this.isFullscreen = isFullscreen;
        
        // 全屏状态改变时调整地图大小
        this.$nextTick(() => {
          if (this.map) {
            this.map.getSize();
            this.map.setCenter(this.map.getCenter());
          }
        });
        
        this.$emit("fullscreen-change", isFullscreen);
      };

      document.addEventListener('fullscreenchange', this.handleFullscreenChange);
      document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange);
      document.addEventListener('mozfullscreenchange', this.handleFullscreenChange);
      document.addEventListener('MSFullscreenChange', this.handleFullscreenChange);
    },

    // 切换全屏状态
    async toggleFullscreen() {
      try {
        if (!this.isFullscreen) {
          // 进入全屏
          const element = this.$refs.mapContainer;
          if (element.requestFullscreen) {
            await element.requestFullscreen();
          } else if (element.webkitRequestFullscreen) {
            await element.webkitRequestFullscreen();
          } else if (element.mozRequestFullScreen) {
            await element.mozRequestFullScreen();
          } else if (element.msRequestFullscreen) {
            await element.msRequestFullscreen();
          }
        } else {
          // 退出全屏
          if (document.exitFullscreen) {
            await document.exitFullscreen();
          } else if (document.webkitExitFullscreen) {
            await document.webkitExitFullscreen();
          } else if (document.mozCancelFullScreen) {
            await document.mozCancelFullScreen();
          } else if (document.msExitFullscreen) {
            await document.msExitFullscreen();
          }
        }
      } catch (error) {
        console.error('全屏操作失败:', error);
        this.$message && this.$message.error('全屏功能不可用');
      }
    },

    // 开始编辑围栏
    startFenceEdit() {
      if (!this.fenceManager) return;
      this.fenceManager.startEdit();
    },

    // 完成编辑
    finishEdit() {
      if (!this.fenceManager) return;
      this.fenceManager.finishEdit();
    },

    // 取消编辑
    cancelEdit() {
      if (!this.fenceManager) {
        this.isEditing = false;
        return;
      }

      // 清除编辑中的临时数据
      this.fenceManager.clear();
      this.fenceManager.isEditing = false;
      this.fenceManager.editPoints = [];
      this.fenceManager.clearMarkers();

      // 恢复原有围栏
      if (this.fenceCoordinates && this.fenceCoordinates.length > 0) {
        this.updateFenceDisplay(this.fenceCoordinates);
      }

      this.isEditing = false;
      this.$emit("edit-end");
    },

    // 更新围栏显示
    updateFenceDisplay(coordinates) {
      if (!this.fenceManager) return;

      if (coordinates && coordinates.length > 0) {
        // 验证坐标数据
        if (validateCoordinates(coordinates)) {
          this.fenceManager.updateFence(coordinates);
          this.hasFence = true;
        } else {
          console.warn("无效的围栏坐标数据:", coordinates);
          this.hasFence = false;
        }
      } else {
        this.fenceManager.clear();
        this.hasFence = false;
      }
    },

    // 处理围栏变更
    handleFenceChange(coordinates, action) {
      this.hasFence = coordinates && coordinates.length > 0;

      this.$emit("fence-change", {
        coordinates: coordinates || [],
        action,
      });

      // 显示操作提示
      if (action === "create") {
        this.$message && this.$message.success("围栏创建成功");
      } else if (action === "update") {
        this.$message && this.$message.success("围栏更新成功");
      }
    },

    // 公共方法：获取地图实例
    getMapInstance() {
      return this.map;
    },

    // 公共方法：设置地图中心
    setCenter(lng, lat) {
      if (this.map) {
        this.map.setCenter([lng, lat]);
      }
    },

    // 公共方法：设置缩放级别
    setZoom(level) {
      if (this.map) {
        this.map.setZoom(level);
      }
    },

    // 公共方法：获取当前围栏坐标
    getFenceCoordinates() {
      if (this.fenceManager) {
        return this.fenceManager.getFenceCoordinates();
      }
      return [];
    },

    // 公共方法：更新围栏
    updateFence(coordinates) {
      this.updateFenceDisplay(coordinates);
    },

    // 公共方法：获取全屏状态
    getFullscreenState() {
      return this.isFullscreen;
    },

    // 公共方法：进入全屏
    enterFullscreen() {
      if (!this.isFullscreen) {
        this.toggleFullscreen();
      }
    },

    // 公共方法：退出全屏
    exitFullscreen() {
      if (this.isFullscreen) {
        this.toggleFullscreen();
      }
    },
  },

  beforeDestroy() {
    // 清理全屏事件监听
    if (this.handleFullscreenChange) {
      document.removeEventListener('fullscreenchange', this.handleFullscreenChange);
      document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange);
      document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange);
      document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange);
    }

    // 如果处于全屏状态，退出全屏
    if (this.isFullscreen) {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    }

    // 清理资源
    if (this.fenceManager) {
      this.fenceManager.destroy();
    }
    if (this.map) {
      this.map.destroy();
    }
  },
};
</script>
<style>
/* .map-controls .el-button {
  color: red !important;
} */
</style>
